package com.kuangstudy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kuangstudy.entity.LoginUser;
import com.kuangstudy.entity.User;
import com.kuangstudy.mapper.MenuMapper;
import com.kuangstudy.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * Author: ryt
 * Version: 1.0
 * Create Date Time: 2021/12/21 15:53.
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    // 根据用户名去查询用户以及查询出用户对应的权限信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1、查询用户的信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(queryWrapper);
        if (StringUtils.isEmpty(user)) {
            // 抛出异常会被 ExceptionTranslationFilter 所捕获！！
            throw new RuntimeException("用户名或者密码输入有误");
        }

        // 2、从数据库中查询用户对应的权限的信息(perms)
        List<String> roles = menuMapper.getMenuByUseId(user.getId());
        List<String> userList = new ArrayList<>(roles);
        // 3、再将用户的权限信息存入到LoginUser对象中
        // 4、封装成UserDetails对象就行返回
        return new LoginUser(user, userList);
    }
}
